package org.web.ssm.utils;


import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.web.ssm.model.wechatModel.TextMessage;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Chambers
 */
public class MessageUtil {
    public static final String MESSAGE_TEXT = "text";
    public static final String MESSAGE_NEWS = "news";
    public static final String MESSAGE_IMAGE = "image";
    public static final String MESSAGE_VOICE = "voice";
    public static final String MESSAGE_VIDEO = "video";
    public static final String MESSAGE_LINK = "link";
    public static final String MESSAGE_LOCATION = "location";
    public static final String MESSAGE_EVENT = "event";
    public static final String MESSAGE_SUBSCRIBE = "subscribe";
    public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
    public static final String MESSAGE_CLICK = "CLICK";
    public static final String MESSAGE_VIEW = "VIEW";
    public static final String MESSAGE_SCANCODE = "scancode_push";

    public static Map<String, String> xmlToMap(HttpServletRequest request)
            throws IOException, DocumentException {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();

        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);

        Element root = doc.getRootElement();

        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();

        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }

        ins.close();
        return map;

    }

    // 文本对象转换为xml方法
    public static String textMessageToXml(TextMessage textMessage) {
        XStream xstream = new XStream();
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }

    public static String initText(String ToUserName, String FromUserName,
                                  String Content) {
        TextMessage text = new TextMessage();
        text.setFromUserName(ToUserName);
        text.setToUserName(FromUserName);
        text.setMsgType(MessageUtil.MESSAGE_TEXT);
        text.setCreateTime(new Date().getTime());
        text.setContent(Content);

        return MessageUtil.textMessageToXml(text);
    }

    // 主菜单
    public static String menuText() {
        StringBuffer sb = new StringBuffer();
        sb.append("欢迎您的关注~等你好久了~~\n");
        sb.append("本微信平台为自主开发，请放心使用。\n");
        sb.append("所有功能请在菜单栏进行点击体验。\n");
        sb.append("直接发送消息即可记账：[午饭花了500] [去超市用了120]，默认为支出~\n");
        sb.append("如果记录收入：[收入 1000]，更多功能请自行体验\n");
        sb.append("发送“菜单”，“menu”可获取本菜单~\n");
        sb.append("更多功能尽请期待...");

        return sb.toString();
    }
}
